//
//  SettingViewController.m
//  999-考勤定位
//
//  Created by 李晓东 on 2018/4/7.
//  Copyright © 2018年 PeanutXu. All rights reserved.
//



#import "SettingViewController.h"
#import "WorkdayViewController.h"
#import "LocationManager.h"
#import "DatabaseManager.h"
#import "Tools.h"
#import <sqlite3.h>

@interface SettingViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *workDayView;
@property (weak, nonatomic) IBOutlet UITextField *officeHourView;
@property (weak, nonatomic) IBOutlet UITextField *offHourView;

@property (nonatomic, strong) UIDatePicker *picker;
@property (nonatomic, strong) GetLocationRuleBlock getLocationRuleBlock;
@property (nonatomic, strong) DatabaseManager *databaseManager;


@end

@implementation SettingViewController{
    int _workday;
    NSMutableString *_mutableStr;
    int _weekdayId;
    NSInteger _officeDate;
    NSInteger _offDate;
}

- (void)loadView{
    [super loadView];
    
    _mutableStr = [NSMutableString string];
    _databaseManager = [DatabaseManager shareDatabaseManager];
    __weak typeof(self) weakSelf = self;
    self.getLocationRuleBlock = ^ (NSArray *array){
        NSDictionary *dict = array.lastObject;
        _workday = [dict[@"weekday"] intValue];
        [weakSelf enumToWeekday:[dict[@"weekday"] intValue]];
        [weakSelf renderView:dict];
        
    };
    _databaseManager.getLocationRuleBlock = self.getLocationRuleBlock;

    [_databaseManager queryInLocationRule];
}

- (void)renderView:(NSDictionary *)dict {
    self.workDayView.text = _mutableStr;

    _weekdayId = [dict[@"id"] intValue];
    NSString *officeHourStr = [Tools transformInDate:[dict[@"office_hour"] integerValue]];
    NSString *offHourStr = [Tools transformInDate:[dict[@"off_hour"] integerValue]];
    self.officeHourView.text = officeHourStr;
    self.offHourView.text = offHourStr;
    
    _officeDate = [Tools transformInSeconds:officeHourStr];
    _offDate = [Tools transformInSeconds:offHourStr];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    [_workDayView setDelegate:self];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getWorkday:) name:@"Workday" object:nil];
    
}

// 监听系统通知中心消息
- (void)getWorkday:(NSNotification *)notification {
    NSDictionary *dict = notification.userInfo;
    NSMutableString *workdayStr = [NSMutableString string];
    _workday = 0;
    for (int i = 0; i < dict.count; i++) {
        
        if ([dict[[NSString stringWithFormat:@"%d", i]] integerValue] > 0 ) {
            switch ([dict[[NSString stringWithFormat:@"%d", i]] integerValue]) {
                case 1:
                    [workdayStr appendString:@"日"];
                    _workday += Sunday;
                    break;
                case 2:
                    [workdayStr appendString:@" 一"];
                    _workday += Monday;
                    break;
                case 3:
                    [workdayStr appendString:@" 二"];
                    _workday += Tuesday;
                    break;
                case 4:
                    [workdayStr appendString:@" 三"];
                    _workday += Wednesday;
                    break;
                case 5:
                    [workdayStr appendString:@" 四"];
                    _workday += Thursday;
                    break;
                case 6:
                    [workdayStr appendString:@" 五"];
                    _workday += Friday;
                    break;
                case 7:
                    [workdayStr appendString:@" 六"];
                    _workday += Saturday;
                    break;
                default:
                    break;
            }
            
        }
        
    }
    
    self.workDayView.text = @"";
    self.workDayView.text = workdayStr;
    
}

- (IBAction)backClick:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

// 确认提交按钮事件
- (IBAction)confirmClick:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"HH:mm"];
    [formatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"]];
    NSTimeInterval currentInterval;
    NSTimeInterval interval;

    if (_weekdayId) {

        [_databaseManager updateInLocationRule:@{@"weekday": [NSNumber numberWithInt:_workday == 0 ? Sunday + Monday + Tuesday + Wednesday + Thursday + Friday + Saturday : _workday], @"office_hour": [NSNumber numberWithInteger:_officeDate], @"off_hour": [NSNumber numberWithInteger:_offDate]}];
    } else {

        [_databaseManager saveInLocationRule:@{@"weekday": [NSNumber numberWithInt:_workday == 0 ? Sunday + Monday + Tuesday + Wednesday + Thursday + Friday + Saturday : _workday], @"office_hour": [NSNumber numberWithInteger:_officeDate], @"off_hour": [NSNumber numberWithInteger:_offDate]}];
    }
//    LocationManager *locationManager = [LocationManager shareLocationManager];
//    [locationManager startLocating];
}

- (int)workdayEnumToInteger:(WorkdayEnum)workday {
    
    return 0;
}

// 点击定位周期,进入工作日选择表
- (IBAction)choseWorkday:(id)sender {

    id controller = [self.storyboard instantiateViewControllerWithIdentifier:@"WorkdayViewController"];
    [controller setChosenDayStr:_mutableStr];
    [self showViewController:controller sender:nil];
}

// textField 不能被点击编辑
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    return NO;
}

// 触发定位时段
- (IBAction)pickDate:(id)sender {
    _picker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0, 0, 1, 240)];
    [_picker setDatePickerMode:UIDatePickerModeTime];
    [_picker setMinuteInterval:2];
    
    UITextField *textField = (UITextField *)sender;
    UIToolbar *toolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 1, 44)];
    UIBarButtonItem *leftBar = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(selected:)];
    UIBarButtonItem *rightBar = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(canceled:)];
    UIBarButtonItem *flexBar = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    [toolbar setItems:@[leftBar, flexBar, rightBar]];
    
    [textField setInputView:_picker];
    [textField setInputAccessoryView:toolbar];

}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"Workday" object:nil];
}

- (void)selected:(id)sender {

    NSDate *date = [_picker date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"HH:mm"];
    NSString *dateStr = [formatter stringFromDate:date];
    
    if ([self.officeHourView isFirstResponder]) {
        [self.officeHourView setText:dateStr];
        [self.officeHourView resignFirstResponder];
        NSInteger officeHourSeconds = [Tools transformInSeconds:[formatter stringFromDate:date]];
        _officeDate = officeHourSeconds;
    } else {
        [self.offHourView setText:dateStr];
        [self.offHourView resignFirstResponder];
        NSInteger offHourSeconds = [Tools transformInSeconds:[formatter stringFromDate:date]];

        _offDate = offHourSeconds;
    }
}

- (void)canceled:(id)sender {
    
}

- (int)weekdayToEnum:(NSString *)weekday{
    
    return 0;
}

- (NSString *)enumToWeekday:(int)weekday{
    NSUInteger length = 0;
    if (weekday == 1)  {
        [_mutableStr insertString:@"日" atIndex:length];
    } else if (weekday >= 2 && weekday < 4) {
        [_mutableStr insertString:@" 一" atIndex:length];
        [self enumToWeekday:weekday - 2];
    } else if (weekday >= 4 && weekday < 8) {
        [_mutableStr insertString:@" 二" atIndex:length];
        [self enumToWeekday:weekday - 4];
    } else if (weekday >= 8 && weekday < 16) {
        [_mutableStr insertString:@" 三" atIndex:length];
        [self enumToWeekday:weekday - 8];
    } else if (weekday >= 16 && weekday < 32) {
        [_mutableStr insertString:@" 四" atIndex:length];
        [self enumToWeekday:weekday - 16];
    } else if (weekday >= 32 && weekday < 64) {
        [_mutableStr insertString:@" 五" atIndex:length];
        [self enumToWeekday:weekday - 32];
    } else if (weekday >= 64) {
        [_mutableStr insertString:@" 六" atIndex:length];
        [self enumToWeekday:weekday - 64];
    }
    
    return @"";
}

@end
